import $ from 'jquery'
import Fire from './Fire'
import getRandom from './getRandom'

/**
 * @description 一个变量
 */
let isAniLoad = false;
const scrollDelay = 300;

function scrollAction() {
  if (isAniLoad) {
      $('.js-ani').each(function () {
          if ($(this).offset().top + scrollDelay < $(window).scrollTop() + window.innerHeight) {
              if ($(this).hasClass('active')) {
              } else {
                  $(this).addClass('active');
              }
          }
          if ($(this).offset().top + $(this).height() < $(window).scrollTop()) {
              $(this).removeClass('active');
          }
          if ($(this).offset().top > $(window).scrollTop() + window.innerHeight) {
              $(this).removeClass('active');
          }
      });
  }
}

function setScale() {
  let width = $('.section1').width();
  let height = $(window).height();

  if (width <= 1366) {
    width = 1366;
  }

  if (width >= 1920) {
    width = 1920
  }

  let wr = height / width;

  if (wr > 9 / 16) {
    $('#bgVideo').height(height).width(height * 16 / 9);
  } else {
    $('#bgVideo').width(width).height(width * 9 / 16);
  }
}

$(() => {
  // intro1 title random
  $('.js-int_title i').each((i, elem) => {
    $(elem).css({
      "transform": `translate(${getRandom(-100, 100)}px,${getRandom(-100, 100)}px)`,
      "transition-delay": +`${getRandom(0, 700) / 1000} + "s"`
    })
  })

  //Scroll
  $(window)
    .scroll(() => {
      scrollAction();
    })
    .resize(() => {
      setScale()
    })

  window.setTimeout(() => {
    isAniLoad = true;
    scrollAction()
  }, 1000)

  // fire
  var canvas = document.getElementById('fire');
  var ctx = canvas.getContext('2d');
  var config = {
    meanSparkLife: 400,
    meanSparkVelocity: [2, 6],
    sparkBlink: 10,
  };

  var resize = window.resize = function () {
    canvas.height = 900;
    canvas.width = document.body.offsetWidth;
  };
  resize();

  var fire = new Fire(ctx, canvas, canvas.height, config);
  var loop = function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    fire.update();
    for (var i = 0; i < 1; i++) {
      fire.spark(Math.random() * canvas.width);
    }
    window.requestAniFrame(loop);
  };
  window.requestAniFrame = function () {
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function (callback) { window.setTimeout(callback, 1000 / 60); };
  }();
  loop();
})